Passing Arrays to Functions
Arrays are commonly used to store collections of data. To work with arrays efficiently, you can pass them to functions. When you pass an array to a function in C, you are essentially passing a pointer to the first element of the array. This allows the function to access and manipulate the original array.
Defining a Function That Takes an Array
To create a function that accepts an array as a parameter, you need to specify the array's data type and size. For example, here's a function printArray that takes an integer array as a parameter:
for (int i = 0; i < size; i++) {
printf(""%d ", arr[i]);
}
}
In this function, int arr[] declares an integer array parameter, and int size specifies the size of the array.
Passing an Array to a Function
In your main function, you can create an array and then pass it to the printArray function along with its size:
int myArray[] = {1, 2, 3, 4, 5};
int arraySize = sizeof(myArray) / sizeof(myArray[0]);
// Pass the array and its size to the string
printArray(myArray, arraySize);
return 0;
}
In this example, we calculate the size of myArray using the sizeof operator and pass both the array and its size to the printArray function.
Example of Passing an Array to a Function
// Function to calculate the sum of an integer array
int sumArray(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int arraySize = sizeof(myArray) / sizeof(myArray[0]);
// Pass the array and its size to the function
int total = sumArray(myArray, arraySize);
printf("Sum of the elements in the array: %d\n", total);
return 0;
}
In this example:
We have a function called sumArray that takes two parameters: an integer array arr and its size size. It calculates the sum of the elements in the array and returns the result.
In the main function, we declare an integer array myArray with some values and calculate its size using the sizeof operator.
We then pass the myArray and its size to the sumArray function by calling sumArray(myArray, arraySize).
The sumArray function processes the array, calculates the sum, and returns it. In the main function, we store the result in the total variable and print it.
Note:- When you run this program, it will calculate and display the sum of the elements in the myArray, demonstrating how to pass an array to a function in C.